﻿Imports System.Xml
Imports System.Resources
Imports System.Globalization
Imports System.Threading
Imports System.Reflection
Imports System.Drawing.Drawing2D
Imports System.ComponentModel

Public Class Form1
    Private GlobalRM As New ResourceManager("WebSitemap_Localizer.Global", Assembly.GetExecutingAssembly())
    Private f As Form
    Private WithEvents bw As BackgroundWorker

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not String.IsNullOrEmpty(My.Settings.Language) Then
            FormTranslator.ChangeFormLanguage(Me, My.Settings.Language)
        End If

        Dim lng As New Languages
        cmbOriginal.ValueMember = "lngIsoCode"
        cmbOriginal.DisplayMember = "lngName"
        cmbOriginal.DataSource = lng.getLanguages()
        lng = Nothing

        Application.DoEvents()

        Dim chk As New Checks
        Storage.IsConnected = chk.isConnectedToInternet()
        chk = Nothing

        If Not Storage.IsConnected Then
            Me.chkTranslate.Enabled = False
        End If
    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If MessageBox.Show(GlobalRM.GetString("SureExit"), GlobalRM.GetString("Exitmsg"), MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) = Windows.Forms.DialogResult.No Then
            e.Cancel = True
        End If
    End Sub

#Region "Menu"

#Region "File"
    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
        Application.Exit()
    End Sub
#End Region

#Region "Tools"
    Private Sub LinguaToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LinguaToolStripMenuItem.Click
        If Language.ShowDialog() = Windows.Forms.DialogResult.OK Then
            If String.IsNullOrEmpty(My.Settings.Language) Then
                FormTranslator.ResetToDefault()
            Else
                FormTranslator.ChangeFormLanguage(Me, My.Settings.Language)
            End If
        End If
    End Sub
#End Region

#Region "Help"
    Private Sub AboutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutToolStripMenuItem.Click
        About.ShowDialog()
    End Sub

    Private Sub OfflineHelpToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OfflineHelpToolStripMenuItem.Click
        Nyi()
    End Sub

    Private Sub GoOnlineToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles GoOnlineToolStripMenuItem.Click
        System.Diagnostics.Process.Start("http://sitemaplocalizer.codeplex.com/documentation")
    End Sub
#End Region

    Private Sub Nyi()
        MsgBox("Not yet implemented")
    End Sub

#End Region

#Region "File/Folder Picker"
    Private Sub btnSource_Click(sender As System.Object, e As System.EventArgs) Handles btnSource.Click
        Me.sourceFilePicker.ShowDialog()
    End Sub

    Private Sub btnDestination_Click(sender As Object, e As EventArgs) Handles btnDestination.Click
        If Me.destFolderPicker.ShowDialog() = Windows.Forms.DialogResult.OK Then
            txtDestination.Text = destFolderPicker.SelectedPath()
            enableDisableButton()
        End If

    End Sub

    Private Sub OpenFileDialog1_FileOk(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles sourceFilePicker.FileOk

        If Me.sourceFilePicker.SafeFileName.ToUpper() = "WEB.SITEMAP" Then
            Me.txtPath.Text = Me.sourceFilePicker.FileName
            enableDisableButton()
        Else
            NotValid()
        End If
    End Sub

    Private Sub enableDisableButton()
        btnLocalize.Enabled = Not String.IsNullOrEmpty(txtPath.Text) And Not String.IsNullOrWhiteSpace(txtDestination.Text)
    End Sub
#End Region

    Private Sub btnLocalize_Click(sender As System.Object, e As System.EventArgs) Handles btnLocalize.Click
        f = New InProgress
        f.WindowState = FormWindowState.Normal
        f.StartPosition = FormStartPosition.CenterParent
        f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
        f.TransparencyKey = Color.Gray
        f.Bounds = Me.Bounds
        f.Width = Me.ClientSize.Width
        f.Height = Me.ClientSize.Height

        errTrans.Clear()

        Storage.LocalizationPath = txtDestination.Text.Trim
        Storage.OriginalFilePath = Me.txtPath.Text.Trim

        'check for autotranslation
        If Me.chkTranslate.Checked Then
            If Not checkForTranslationParams() Then
                Exit Sub
            End If
        End If
        bw = New BackgroundWorker()

        bw.RunWorkerAsync(Me.chkTranslate.Checked)

        f.ShowDialog()
    End Sub

#Region "Localization tasks"
    Private Sub localizeTask(sender As Object, e As DoWorkEventArgs) Handles bw.DoWork
        Try
            Dim localize As Boolean = Boolean.TryParse(e.Argument, New Boolean)

            Dim xmld As New XmlDocument()
            xmld.Load(Storage.OriginalFilePath)

            Dim newSiteMap As XmlDocument = xmld.Clone()

            Dim root As XmlNode = newSiteMap.SelectNodes("/").Item(0)
            Dim siteMapNodes As XmlNodeList
            For Each node As XmlNode In root.ChildNodes
                If node.Name = "siteMap" Then
                    Dim attr As XmlNode = newSiteMap.CreateNode(XmlNodeType.Attribute, "enableLocalization", "")
                    attr.Value = "true"
                    node.Attributes.SetNamedItem(attr)

                    siteMapNodes = node.ChildNodes()
                Else
                    'nothing to do
                End If
            Next

            If Not siteMapNodes Is Nothing And siteMapNodes.Count = 0 Then
                'NotValid()
                e.Result = False
            Else
                Dim loc As New Localizator
                loc.localize(siteMapNodes, newSiteMap, localize)
            End If

            Writer.writeSitemap(newSiteMap)
            e.Result = True
        Catch ex As Exception
            'Here it goes the error management
            e.Result = False
        End Try
    End Sub

    Private Sub NotValid()
        Dim message As String = GlobalRM.GetString("NotValid")
        Dim title As String = GlobalRM.GetString("Errormsg")
        MsgBox(message, MsgBoxStyle.Critical, title)
    End Sub

    Private Function checkForTranslationParams() As Boolean
        Dim isOk As Boolean = True

        'check on the original language
        If String.IsNullOrEmpty(cmbOriginal.SelectedValue) Then
            errTrans.SetError(cmbOriginal, GlobalRM.GetString("SelectOriginalLanguage"))
            isOk = False
            Storage.OriginalLanguage = String.Empty
        Else
            Storage.OriginalLanguage = cmbOriginal.SelectedValue.ToString
        End If

        'check the textbox
        Try
            If Not String.IsNullOrEmpty(txtIsoCode.Text) Then
                txtIsoCode.Text = txtIsoCode.Text.TrimEnd(",").TrimStart(",")
                Dim languagesText As String() = txtIsoCode.Text.Replace(" ", "").Split(",")
                For Each lang As String In languagesText
                    If lang.Length > 2 Or lang.Length < 2 Then
                        isOk = False
                        errTrans.SetError(txtIsoCode, GlobalRM.GetString("InvalidIsoCode"))
                        Exit For
                    End If
                Next
                Storage.TranslationLanguages = languagesText
            End If
        Catch ex As Exception
            errTrans.SetError(txtIsoCode, GlobalRM.GetString("InvalidIsoCode"))
            isOk = False
        End Try

        'check on the selected language, only if the textbox is empty        
        Dim languages As New ArrayList
        If chkEN.Checked Then
            languages.Add("en")
        End If
        If chkIT.Checked Then
            languages.Add("it")
        End If
        If chkDE.Checked Then
            languages.Add("de")
        End If
        If chkFR.Checked Then
            languages.Add("fr")
        End If
        If chkES.Checked Then
            languages.Add("es")
        End If
        If chkPT.Checked Then
            languages.Add("pt")
        End If
        If languages.Count = 0 Then
            If String.IsNullOrEmpty(txtIsoCode.Text) Then
                errTrans.SetError(lblTranLang, GlobalRM.GetString("SelectTransLanguage"))
                Storage.TranslationLanguages = New String() {}
                isOk = False
            End If
        Else
            If (Storage.TranslationLanguages Is Nothing OrElse Storage.TranslationLanguages.Count = 0) Then
                Storage.TranslationLanguages = languages.ToArray(GetType(String))
            Else
                Storage.TranslationLanguages = Storage.TranslationLanguages.Concat(languages.ToArray(GetType(String))).ToArray()
            End If
        End If

        Return isOk
    End Function
#End Region

    Private Sub chkTranslate_CheckedChanged(sender As Object, e As EventArgs) Handles chkTranslate.CheckedChanged
        If chkTranslate.Checked Then
            Me.Width = Me.Width + 200
        Else
            Me.Width = Me.Width - 200
        End If
    End Sub

    Private Sub WorkDone(sender As Object, e As RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted
        f.Close()
        f.Dispose()

        If (e.Result) Then
            'well done
            Dim message As String = GlobalRM.GetString("Finished")
            Dim title As String = GlobalRM.GetString("OK")
            MsgBox(message, MsgBoxStyle.Information, title)
        Else
            NotValid()
        End If

    End Sub





End Class
